import requests
import pymongo
from twisted.internet.defer import timeout

requests.adapters.DEFAULT_RETRIES = 5

class TestifyAvailable:
    
    testifyIp = 'https://www.baidu.com'
    timeout = 10
    
    def __init__(self):
        self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
        if "proxy" not in self.myclient.database_names():
            raise Exception("不存在[proxy]数据库")
        self.mydb = self.myclient["proxy"]
        if "proxy_kuai" not in self.mydb.list_collection_names():
            raise Exception("不存在[proxy_kuai]集合")
        self.mycol = self.mydb["proxy_kuai"]

    def testifyDBIPAvailable(self):
        for proxyIpObject in self.mycol.find():
            proxy = { proxyIpObject['type']: proxyIpObject['ip']+':' + proxyIpObject['port'] }
            result = self.testifyIPAvailable(self.testifyIp, proxy, self.timeout)
            if not result:
                self.mycol.update_one({ 'ip': proxyIpObject['ip'] , 'port': proxyIpObject['port'] }, { '$set': { 'isDeleted': 1 } })

    def testifyIPAvailable(self,testifyIp, proxyIpObject, timeout):
        response = requests.get(testifyIp,proxies=proxyIpObject,timeout=timeout)
        if not response.ok:
            print(str(proxyIpObject) + '失效')
        else:
            print(str(proxyIpObject) + '有效')
        return response.ok
    
    def close(self):
        self.myclient.close()